#include "lib/string.h"
#include "config/type.h"

void *memcpy(void *des, const void *src, unsigned int n) {
	unsigned char *sp = (unsigned char *)src;
	unsigned char *dp = (unsigned char *)des;
	for (; n != 0; n--) {
		*dp++ = *sp++;
	}
	return des;
}

int memcmp(const void *des, const void *src, unsigned int n) {
	unsigned char *dp = (unsigned char *)des;
	unsigned char *sp = (unsigned char *)src;
	while (n-- > 0) {
		if (*dp != *sp)
			return *dp - *sp;
		dp++;
		sp++;
	}

	return 0;
}

void *memmove(void *des, const void *src, unsigned int n) {
	const char *sp = src;
	char *dp = des;

	if (n == 0)
		return des;

	if (sp < dp && sp + n > dp) {
		sp += n;
		dp += n;
		while (n-- > 0)
			*--dp = *--sp;
	} else
		while (n-- > 0)
			*dp++ = *sp++;

	return des;
}

void *memset(void *des, unsigned char value, unsigned int n) {
	unsigned char *dp = (unsigned char *)des;
	for (; n != 0; n--) {
		*dp++ = value;
	}
	return des;
}

int strlen(const char *str) {
	int len = 0;
	while (*str++) {
		len++;
	}
	return len;
}

int strcmp(const char *str1, const char *str2) {
	while (*str1 || *str2) {
		if (*str1 == *str2) {
			str1++;
			str2++;
		} else {
			return (*str1 - *str2);
		}
	}
	return 0;
}

char *strcpy(char *des, const char *src) {
	char *res = des;
	while (*src) {
		*des++ = *src++;
	}
	*des = '\0';
	return res;
}

// 保证以 NUL 为终点
char *safestrcpy(char *des, const char *src, int n) {
	char *res = des;
	if (n <= 0)
		return res;
	while (--n > 0 && (*des++ = *src++) != 0)
		;
	*des = 0;
	return res;
}

char *strcat(char *des, const char *src) {
	char *res = des;
	while (*des) {
		des++;
	}

	while (*src) {
		*des++ = *src++;
	}
	return res;
}

char *strstr(const char *str, const char *target) {
	char *tp = (char *)target;
	while (*str) {
		while ((!*tp) || *str == *tp) {
			if (!*tp) {
				return (char *)str;
			}
			str++;
			tp++;
		}
		tp = (char *)target;
		str++;
	}
	return "";
}

int atoi(const char *src) {
	int s = 0;
	bool isMinus = false;
	while (*src == ' ') {
		src++;
	}
	if (*src == '+' || *src == '-') {
		if (*src == '-') {
			isMinus = true;
		}
		src++;
	} else if (*src < '0' || *src > '9') {
		s = 0;
		return s;
	}
	while (*src != '\0' && *src >= '0' && *src <= '9') {
		s = s * 10 + *src - '0';
		src++;
	}
	return s * (isMinus ? -1 : 1);
}
